package com.roubsite.cloud.common.userinfo;

import com.roubsite.cloud.common.service.RedisService;
import com.roubsite.cloud.common.utils.RSAUtils;
import com.roubsite.cloud.common.utils.SpringUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

@Component
public class RCUserUtils {
	private static RCUserUtils instance;

	@Autowired
	RedisService redisService;

	public SecurityUserDetails getUserInfo(String token) {
		try {
			return (SecurityUserDetails) redisService.getFromRedis("token" + RSAUtils.decrypt(token));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}
	public SecurityUserDetails getUserInfo(ServerHttpRequest request) {
		try {
			if(ObjectUtils.isNotEmpty(request)){
				String token = request.getHeaders().getFirst("Authorization");
				if (StringUtils.isNotEmpty(token)) {
					token = token.substring("Bearer ".length());
					return (SecurityUserDetails) redisService.getFromRedis("token" + RSAUtils.decrypt(token));
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}
	public static RCUserUtils getInstance(){
		if (instance == null) {
			synchronized (RCUserUtils.class) {
				if (instance == null) {
					// 在第一次调用getInstance方法时创建实例
					instance = SpringUtil.getApplicationContext().getBean(RCUserUtils.class);
				}
			}
		}
		return instance;
	}

}
